package com.sunda.spmsweb.wmscontroller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sunda.spmscommon.Constans;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsweb.util.JWTUtil;
import com.sunda.spmswms.entity.PositionMoveRequest;
import com.sunda.spmswms.entity.WhsStorageInventory;
import com.sunda.spmswms.service.IWhsOperateLogService;
import com.sunda.spmswms.service.IWhsStorageInventoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

import static com.sunda.spmscommon.Constans.WhsOperateLog_DocumentType_NanShaStorageLog;
import static com.sunda.spmscommon.Constans.WhsOperateLog_DocumentType_OverSeaStorageLog;

/**
 * @description:
 * @author: Johnny Zhao
 * @time: 2021/5/14 12:42
 */
@RestController
@RequestMapping("/WhsPositionMove")
@Api(tags = "库房移位信息", description = "库房移位信息")
public class WhsPositionMoveController {

    @Autowired
    IWhsStorageInventoryService iWhsStorageInventoryService;
    @Autowired
    IWhsOperateLogService iWhsOperateLogService;

    @RequestMapping("/whsPositionMove")
    @ApiOperation(value = "获得移位信息", httpMethod = "POST")
    public ResponseResult getPositionList(@RequestBody JSONObject searchCriteria) {
        List<String> boxNoteList = searchCriteria.containsKey("boxNoteList") ? (List) searchCriteria.getJSONArray("boxNoteList") : null;
        System.out.println(boxNoteList);
        List<WhsStorageInventory> whsStorageInventoryList = iWhsStorageInventoryService.getStorageListByBoxNoteList(boxNoteList);

        return ResponseResult.success().add("key", whsStorageInventoryList.toString());
    }


    @RequestMapping("/whsPositionMoveRequest")
    @ApiOperation(value = "上传移位信息", httpMethod = "POST", notes = "每行错误代码（RowCode）含义：\n\t2000：PDA提交数据时间格式正常，且晚于SPMS系统记录时间，代表为最新记录，写入数据库\n" +
            "\t1500: SPMS系统已有箱码储位记录，时间格式正确，且时间晚于PDA提交时间，证明非最新库位状态，该条PDA提交记录丢弃\n" +
            "\t1000: PDA提交系统的记录日期格式有问题，SPMS系统直接修改为正确格式且录入结果\n" +
            "\t3000: SPMS系统没有此箱号的操作记录，直接采用该PDA操作记录新建该箱号上架记录，数量为1,\n" +
            "\t提交信息格式为：\n" + "{\n" +
            "\t\"data\": [{\n" +
            "\t\t\t\"boxNo\": \"ZX-10215800004-0303\",\n" +
            "\t\t\t\"uuid\": \"b95946ac1dab42b79ade3438acb0b513\",\n" +
            "\t\t\t\"operateTime\": \"2021-04-22 14:08:29\",\n" +
            "                        \"comments\":\"\"\n" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"boxNo\": \"TEST-1001-0101\",\n" +
            "\t\t\t\"uuid\": \"b95946ac1dab42b79ade3438acb0b53i\",\n" +
            "\t\t\t\"operateTime\": \"2021-04-20 12:09:28\",\n" +
            "                        \"comments\":\"\"\n" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"boxNo\": \"ZF-10fff-ff0101\",\n" +
            "\t\t\t\"uuid\": \"b95946ac1dab42b79ade3438acb0b512\",\n" +
            "\t\t\t\"operateTime\": \"2021-04-22 12:08:29\",\n" +
            "                        \"comments\":\"\"\n" +
            "\t\t}\n" +
            "\n" +
            "\t]\n" +
            "}")
    public ResponseResult positionMoveResult(@RequestBody JSONObject storageList) {
        JSONArray prListJson = storageList.containsKey("data") ? storageList.getJSONArray("data") : null;
        List<PositionMoveRequest> prList = (List<PositionMoveRequest>) JSONArray.parseArray(prListJson.toJSONString(), PositionMoveRequest.class);
        Iterator it = prList.iterator();
        List<PositionMoveRequest> prResult = new ArrayList<>();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        while (it.hasNext()) {
            PositionMoveRequest pmr = (PositionMoveRequest) it.next();
            System.out.println("提交箱码录入的储位为" + pmr.getUuid());
            if (pmr.getOperateTime() != null && pmr.getOperateTime().matches("^[1-3]\\d+-\\d+-\\d+ \\d+:\\d+:\\d+")) {
                try {
                    Optional<WhsStorageInventory> wsi = iWhsStorageInventoryService.getStorageInventoryByBoxNo(pmr.getBoxNo());
                    if (wsi.isPresent()) {
                        String opt = wsi.get().getOperateTime();
                        System.out.println("系统时间为" + opt);
                        if (opt != null && opt.matches("^[1-3]\\d+-\\d+-\\d+ \\d+:\\d+:\\d+")) {
                            if (df.parse(pmr.getOperateTime()).after(df.parse(opt))) {
                                PositionMoveRequest prResultEl = new PositionMoveRequest();
                                iWhsStorageInventoryService.updateStorageInventoryX(pmr.getUuid(), pmr.getOperateTime(), pmr.getBoxNo());
                                prResultEl.setUuid(pmr.getUuid());
                                prResultEl.setBoxNo(pmr.getBoxNo());
                                prResultEl.setOperateTime(pmr.getOperateTime());
                                String s = String.format("提交日期%S晚于系统日期%S，已完成更新", pmr.getOperateTime(), opt);
                                prResultEl.setComments(s);
                                prResultEl.setRowCode(2000);
                                prResult.add(prResultEl);
                                System.out.println("已完成更新");
                            } else {
                                PositionMoveRequest prResultEl = new PositionMoveRequest();
                                prResultEl.setUuid(pmr.getUuid());
                                prResultEl.setBoxNo(pmr.getBoxNo());
                                prResultEl.setOperateTime(pmr.getOperateTime());
                                String s = String.format("提交日期%S早于或等于系统日期%S，已放弃更新", pmr.getOperateTime(), opt);
                                prResultEl.setComments(s);
                                prResultEl.setRowCode(1500);
                                prResult.add(prResultEl);
                                System.out.println("不需要更新");
                            }
                        } else {
                            PositionMoveRequest prResultEl = new PositionMoveRequest();
                            iWhsStorageInventoryService.updateStorageInventoryX(pmr.getUuid(), pmr.getOperateTime(), pmr.getBoxNo());
                            prResultEl.setUuid(pmr.getUuid());
                            prResultEl.setBoxNo(pmr.getBoxNo());
                            prResultEl.setOperateTime(pmr.getOperateTime());
                            String s = String.format("原时间%S不正确，已修改为正确时间%S", opt, pmr.getOperateTime());
                            prResultEl.setComments(s);
                            prResultEl.setRowCode(1000);
                            prResult.add(prResultEl);
                            System.out.println("系统更新为提交的时间并纠正格式");
                        }
                    } else {
                        PositionMoveRequest prResultEl = new PositionMoveRequest();
                        System.out.println("系统未查找到此项");
                        iWhsStorageInventoryService.insertStorageInventory(pmr.getUuid(), pmr.getOperateTime(), pmr.getBoxNo());
                        prResultEl.setUuid(pmr.getUuid());
                        prResultEl.setBoxNo(pmr.getBoxNo());
                        prResultEl.setOperateTime(pmr.getOperateTime());
                        prResultEl.setComments("此行为新建");
                        prResultEl.setRowCode(3000);
                        prResult.add(prResultEl);
                        System.out.println("此行在系统内新建");
                    }
                } catch (Exception e) {
                    return ResponseResult.error(e.getMessage());
                }
            } else {
                PositionMoveRequest prResultEl = new PositionMoveRequest();
                prResultEl.setUuid(pmr.getUuid());
                prResultEl.setBoxNo(pmr.getBoxNo());
                prResultEl.setOperateTime(pmr.getOperateTime());
                String s = String.format("上架提交项时间%S不正确，此项未提交成功！", pmr.getOperateTime());
                prResultEl.setComments(s);
                prResultEl.setRowCode(4000);
                prResult.add(prResultEl);
                System.out.println("发生错误，此行提交未成功");
            }
        }
        return ResponseResult.success().add("返回结果列表", prResult);
    }

    @RequestMapping("/whsPositionMoveX")
    @ApiOperation(value = "备件货仓库内移位", httpMethod = "POST", notes = "备件货仓库内移位\n" +
            "{\n" +
            "  \"werks\":\"CN01\",\n" +
            "  \"whsLocationCode\":\"1061\",\n" +
            "  \"boxNote\":\"BJ-9485738922\",\n" +
            "  \"sourceStorageUuid\":\"sources storage uuid\",\n" +
            "  \"targetStorageUuid\":\"target storage uuid\",\n" +
            "  \"operateQty\":1\n" +
            "}")
    public ResponseResult whsPositionMoveX(@RequestBody JSONObject posMoveObj) {
        try {
            String werks = posMoveObj.getString("werks");
            String whsLocationCode = posMoveObj.getString("whsLocationCode");
            String boxNote = posMoveObj.getString("boxNote");
            String sourceStorageUuid = posMoveObj.getString("sourceStorageUuid");
            String targetStorageUuid = posMoveObj.getString("targetStorageUuid");
            double operateQty = posMoveObj.containsKey("operateQty") ? posMoveObj.getDouble("operateQty") : -1;

            if (StringUtils.isEmpty(werks) || StringUtils.isEmpty(whsLocationCode) ||
                    StringUtils.isEmpty(boxNote) || StringUtils.isEmpty(sourceStorageUuid) || StringUtils.isEmpty(targetStorageUuid) || operateQty <= 0) {
                return ResponseResult.error("Please check your paramaters");
            }

            String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
            WhsStorageInventory whsStorageInventory = iWhsStorageInventoryService.getStorageBoxNote(sourceStorageUuid, boxNote);
            if (null == whsStorageInventory) {
                return ResponseResult.error("The given boxNote: " + boxNote + " does not exist on storage: " + sourceStorageUuid);
            }

            // 从原储位下加，并加日志
            if (iWhsStorageInventoryService.deleteStorageByBoxNoteStorageId(sourceStorageUuid, boxNote) < 0) {
                return ResponseResult.error("error for " + boxNote + " on storage, storageUuid: " + sourceStorageUuid);
            }
            iWhsOperateLogService.insertWhsOperateLog(
                    WhsOperateLog_DocumentType_NanShaStorageLog,
                    sourceStorageUuid,
                    "",
                    boxNote,
                    1,
                    Constans.WhsOperateLog_OperationType_ShelfOff,
                    "",
                    Constans.WHS_PositionMove_ShelfOff,
                    userId,
                    Constans.WHS_PositionMove,
                    werks,
                    whsLocationCode);

            //在目标储位上架，并加日志
            iWhsStorageInventoryService.insertStorageInventory(targetStorageUuid, "", boxNote);
            iWhsOperateLogService.insertWhsOperateLog(
                    WhsOperateLog_DocumentType_NanShaStorageLog,
                    targetStorageUuid,
                    "",
                    boxNote,
                    1,
                    Constans.WhsOperateLog_OperationType_ShelfOn,
                    "",
                    Constans.WHS_PositionMove_ShelfOn,
                    userId,
                    Constans.WHS_PositionMove,
                    werks,
                    whsLocationCode);
            return ResponseResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error(e.getMessage());
        }

    }
    @RequestMapping("/whsPositionMoveM")
    @ApiOperation(value = "贸易货仓库内移位", httpMethod = "POST", notes = "贸易货仓库内移位\n" +
            "{\n" +
            "  \"werks\":\"CN01\",\n" +
            "  \"whsLocationCode\":\"1061\",\n" +
            "  \"materialNo\":\"maerial no\",\n" +
            "  \"sourceStorageUuid\":\"sources storage uuid\",\n" +
            "  \"targetStorageUuid\":\"target storage uuid\",\n" +
            "  \"operateQty\":12\n" +
            "}")
    @Transactional(rollbackFor = Exception.class)
    public synchronized ResponseResult whsPositionMoveM(@RequestBody JSONObject posMoveObj) {
        try {
            String werks = posMoveObj.getString("werks");
            String whsLocationCode = posMoveObj.getString("whsLocationCode");
            String materialNo = posMoveObj.getString("materialNo");
            String sourceStorageUuid = posMoveObj.getString("sourceStorageUuid");
            String targetStorageUuid = posMoveObj.getString("targetStorageUuid");
            double operateQty = posMoveObj.containsKey("operateQty") ? posMoveObj.getDouble("operateQty") : -1;

            if (StringUtils.isEmpty(werks) || StringUtils.isEmpty(whsLocationCode) ||
                    StringUtils.isEmpty(materialNo) || StringUtils.isEmpty(sourceStorageUuid) || StringUtils.isEmpty(targetStorageUuid) || operateQty <= 0) {
                return ResponseResult.error("Please check your paramaters");
            }

            String documentType = "CN01".equals(werks) ? WhsOperateLog_DocumentType_NanShaStorageLog : WhsOperateLog_DocumentType_OverSeaStorageLog;
            String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());

            // 检查可出的库存
            JSONObject storageObj=new JSONObject();
            storageObj.put("storageUuid",sourceStorageUuid);
            storageObj.put("qty",operateQty);
            JSONArray tempStorage=new JSONArray();
            tempStorage.add(storageObj);
            ResponseResult checkInvRes = iWhsStorageInventoryService.checkStorageInventory(tempStorage, materialNo);
            if (checkInvRes.getCode() != 200) {
                throw new Exception(checkInvRes.getMsg());
            }

            // 从原储位下加，并加日志
            if (iWhsStorageInventoryService.updateWhsStorage(sourceStorageUuid, materialNo, operateQty) < 0) {
                throw new Exception("Update Storage Inventory failed for " + materialNo + " on storage Info, storageUuid: " +
                        sourceStorageUuid +
                        ", qty: " + operateQty);
            }


            iWhsOperateLogService.insertWhsOperateLog(
                    documentType,
                    sourceStorageUuid,
                    materialNo,
                    "",
                    operateQty,
                    Constans.WhsOperateLog_OperationType_ShelfOff,
                    "",
                    Constans.WHS_PositionMove_ShelfOff,
                    userId,
                    Constans.WHS_PositionMove,
                    werks,
                    whsLocationCode);

            //在目标储位上架，并加日志
            if (iWhsStorageInventoryService.updateWhsStorageInventoryMOld(targetStorageUuid, materialNo, operateQty) < 0) {
                throw new Exception("Update Storage Inventory failed for " + materialNo + " on storage Info, storageUuid: " +
                        targetStorageUuid +
                        ", qty: " + operateQty);
            }
            iWhsOperateLogService.insertWhsOperateLog(
                    documentType,
                    targetStorageUuid,
                    materialNo,
                    "",
                    operateQty,
                    Constans.WhsOperateLog_OperationType_ShelfOn,
                    "",
                    Constans.WHS_PositionMove_ShelfOn,
                    userId,
                    Constans.WHS_PositionMove,
                    werks,
                    whsLocationCode);
            return ResponseResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error(e.getMessage());
        }

    }


}
